package com.miracle.java2110.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.miracle.java2110.common.PageVo;
import com.miracle.java2110.common.R;
import com.miracle.java2110.mapper.DrinksMapper;
import com.miracle.java2110.pojo.Drinks;
import com.miracle.java2110.service.DrinksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author rwg
 */
@Service("drinksService")
public class DrinksServiceImpl implements DrinksService {

    @Autowired
    private DrinksMapper drinksMapper;

    @Override
    public List<Drinks> findDrinks() {
        return drinksMapper.selectByExample(null);
    }

    @Override
    public PageVo<Drinks> getPageData(Map<String, Object> params) {
        // 使用 mybatis 分页插件
        PageHelper.startPage(Integer.parseInt(params.get("page") + ""), Integer.parseInt(params.get("limit") + ""));

        List<Drinks> drinks = drinksMapper.selectByParams(params);

        PageInfo<Drinks> drinksPageInfo = new PageInfo<>(drinks);

        // 把分页数据封装到自定义的分页对象中 因为 layui 要求的 json 数据格式就是 PageVo
        PageVo<Drinks> drinksPageVo = new PageVo<>();

        drinksPageVo.setCode(0);
        drinksPageVo.setMsg("查询分页数据");
        drinksPageVo.setCount(drinksPageInfo.getTotal());
        drinksPageVo.setData(drinksPageInfo.getList());

        return drinksPageVo;
    }

    @Override
    public R deleteById(Integer did) {

        int result = drinksMapper.deleteByPrimaryKey(did);

        if (result == 1) {
            return R.ok(200, "删除成功");
        } else {
            return R.error(400, "删除失败");
        }

    }

    @Override
    public R updateById(Drinks drinks) {
        int result = drinksMapper.updateByPrimaryKey(drinks);

        if (result == 1) {
            return R.ok(200, "修改成功");
        } else {
            return R.error(400, "修改失败");
        }

    }

    @Override
    public R addUser(Drinks drinks) {
        int result = drinksMapper.insertSelective(drinks);

        if (result == 1) {
            return R.ok(200, "添加成功");
        } else {
            return R.error(400, "添加失败");
        }

    }
}
